﻿using EnterpriseWebsiteApi.ActionFilters;
using EnterpriseWebsiteApi.ActionResults;
using EnterpriseWebsiteApi.Dto.AboutUs;
using EnterpriseWebsiteBLL;
using EnterpriseWebsiteUtil.Helper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace EnterpriseWebsiteApi.Controllers.Admin
{
    [Route("api/admin/[controller]/[action]")]
    [ApiController]
    [TypeFilter(typeof(JwtAuthorizeFilter))]
    public class AboutUsController : ControllerBase
    {
        private readonly AboutUsService _aboutUsService;
        private readonly Mapper _mapper;

        public AboutUsController(AboutUsService aboutUsService, Mapper mapper)
        {
            _aboutUsService = aboutUsService;
            _mapper = mapper;
        }

        [HttpGet]
        public async Task<ActionResult> GetAll()
        {
            try
            {
                var entities = await _aboutUsService.GetAllAsync();
                var dtos = _mapper.MapList<AboutUsQueryDto>(entities);
                return new Success(dtos);
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }

        /// <summary>
        /// 根据ID获取关于我们
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> GetAboutUsById(int id)
        {
            try
            {
                var entity = await _aboutUsService.GetByIdAsync(id);
                if (entity == null)
                {
                    return new Error($"关于我们Id {id} 不存在");
                }
                return new Success(entity);
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }

        [HttpPost]
        public async Task<ActionResult> UpdateContent(AboutUsUpdateContentDto dto)
        {
            try
            {
                var entity = await _aboutUsService.GetByIdAsync(dto.Id);
                if (entity == null)
                {
                    throw new Exception("关于我们类型不存在");
                }
                entity = _mapper.Map(dto, entity);
                await _aboutUsService.UpdateContentAsync(entity);
                return new Success();
            }
            catch (Exception ex)
            {
                return new Error(ex);
            }
        }

        /// <summary>
        /// 上传媒体
        /// </summary>
        /// <param name="mediaFile"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<WangEditorUploadDto>> UploadMedia(IFormFile mediaFile)
        {
            try
            {
                WangEditorUploadDataDto editorUploadData = new WangEditorUploadDataDto();

                if (mediaFile == null)
                {
                    return Ok(new WangEditorUploadDto() { errno = 1,message = "未有上传文件" });
                }

                string mediaType = Path.GetExtension(mediaFile.FileName).ToLower();

                if (mediaFile.Length > 6 * 1024 * 1024)
                {
                    return Ok(new WangEditorUploadDto() { errno = 1, message = "上传文件大小不能超过6mb" });
                }

                string fileName = $"{Guid.NewGuid()}{mediaType}";
                string folderPath = Path.Combine("wwwroot", "aboutUs");
                string filePath = Path.Combine("wwwroot", "aboutUs", fileName);

                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                using (FileStream stream = new FileStream(filePath, FileMode.Create))
                {
                    await mediaFile.CopyToAsync(stream);
                }

                string baseUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}";
                string mediaUrl = $"/aboutUs/{fileName}";
                editorUploadData.url = $"{baseUrl}{mediaUrl}";
                return Ok(new WangEditorUploadDto() { errno = 0, data = editorUploadData });
            }
            catch (Exception ex)
            {
                return Ok(new WangEditorUploadDto() { errno = 1, message = ex.ToString()});
            }
        }
    }
}
